var express = require('express');
var router = express.Router();
const CloudSDK = require('leancloud-storage');
const { getTokenWithCache } = require('../utils/push_token');
const axios = require('axios')
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    console.log('====================================');
    console.log("拦截器",response.data);
    console.log('====================================');
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    console.log("错误",error);
    
    return Promise.reject(error);
  });

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

//图片转存服务接口
router.post('/upload',async function(req, res, next) {
  let base64 = req.body.base64;
  let cloudRes = await new CloudSDK.File('avatar.png',{base64}).save()
  let url = cloudRes.attributes.url
  res.send({
    code:1,
    msg:'图片上传成功',
    url
  })
});


router.get('/push/message',async(req,res)=>{
  // 1. 获取authToken
  let token = await getTokenWithCache()
  // console.log("token令牌：",token);
  let {title,content,pushToken} = req.query  //提取客户端提交的get参数

  // res.send(token)
  let projectId = '461323198430416082'  //AGC平台获取自己的项目ID
  let url = `https://push-api.cloud.huawei.com/v3/${projectId}/messages:send`
  // 消息推送的数据包格式一定要按照文档的要求来设置
  let bodyData = {
    "payload": {
      "notification": {
        "category": "MARKETING",// 替换为实际消息类型
          "title": title,
          "body": content,
          "clickAction": {
            "actionType": 0  //点击通知后打开应用首页
          },
      }
    },
    "target": {
      "token": [`${pushToken}`]
    },
    "pushOptions": {
      "testMessage": true,
      "ttl": 86400
    }
  }

  let result = await axios.post(url,bodyData,{
    headers:{
      "Content-Type": "application/json",
      "Authorization": `Bearer ${token}`,
      "push-type": 0
    }
  })
  let msg = result.data.code==="80000000" ? "推送成功" :"推送失败"
  res.send({msg})
  console.log('====================================');
  console.log("发送结果",result.data);
  console.log('====================================');
})

module.exports = router;
